<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="套餐名" prop="packageName">
        <el-input
          v-model="queryParams.packageName"
          placeholder="请输入套餐名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="套餐价格" prop="packagePrice">
        <el-input
          v-model="queryParams.packagePrice"
          placeholder="请输入套餐价格"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="套餐状态" prop="packageStatus">
        <el-input
          v-model="queryParams.packageStatus"
          placeholder="请输入套餐状态"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:package:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:package:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:package:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:package:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="packageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="套餐id" align="center" prop="packageId" /> -->
      <el-table-column label="套餐名" align="center" prop="packageName" />
      <el-table-column label="套餐图片" align="center" prop="packagePicture" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.packagePicture" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="套餐价格" align="center" prop="packagePrice" />
      <!-- <el-table-column label="套餐状态" align="center" prop="packageStatus" /> -->

        <el-table-column label="套餐状态" align="center" prop="packageStatus" >
        <template slot-scope="scope">
          <el-tooltip :content="'灰色代表禁用'" placement="top">
            <el-switch
              v-model="scope.row.packageStatus"
              inactive-color= "#909399"
               active-color="#409EFF"
               active-value=1
               inactive-value=0
              @change="handleSwitchChange(scope.row)" >
            </el-switch>
          </el-tooltip>
        </template>
      </el-table-column>




      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">

        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:package:edit']"
          >修改</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleProductUpdate(scope.row)"
            v-hasPermi="['system:package:edit111']"
          >配置商品</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:package:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>



    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

      <!--  配置商品 -->

      <el-dialog :title="title" :visible.sync="openProduct" width="800px" append-to-body>
  <div>
    <el-spinner v-if="loading" size="large" class="spinner"></el-spinner>
    <el-container v-else>
      <el-row>
        <el-col v-for="product in productList" :key="product.productId" :span="8">
          <el-card class="product-card" :body-style="{ padding: '20px' }">
            <el-checkbox
              :checked="isProductSelected(product.productId)"
              @change="handleProductSelection(product)"
              class="product-checkbox"
            >
              <img :src="product.productPhoto" alt="Product Photo" class="product-image" />
              <div class="product-info">
                <h3>{{ product.productName }}</h3>
                <p>单价: {{ product.price }}</p>
                <div class="product-quantity" v-if="isProductSelected(product.productId)">
                  <el-input
                    :value="getProductQuantity(product.productId)"
                    @input="value => updateProductQuantity(product.productId, value)"
                    type="number"
                    min="1"
                    size="small"
                    placeholder="数量"
                    style="width: 100px;"
                  />
                </div>
              </div>
            </el-checkbox>
          </el-card>
        </el-col>
      </el-row>
    </el-container>
  </div>
  <span slot="footer" class="dialog-footer">
    <el-button @click="openProduct = false">取消</el-button>
    <el-button type="primary" @click="saveSelectedProducts">保存</el-button>
  </span>
</el-dialog>





    <!-- 添加或修改套餐管理对话框 -->
    <el-dialog :title="title" :visible.sync="openPackage" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="套餐名" prop="packageName">
          <el-input v-model="form.packageName" placeholder="请输入套餐名" />
        </el-form-item>
        <el-form-item label="套餐图片" prop="packagePicture">
          <image-upload v-model="form.packagePicture"/>
        </el-form-item>
        <el-form-item label="套餐价格" prop="packagePrice">
          <el-input v-model="form.packagePrice"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPackage, getPackage, delPackage, addPackage, updatePackage, listProduct, addPackageProduct, getPackageAssociation } from "@/api/system/package";



export default {
  name: "Package",
  data() {
    return {

      // 遮罩层
      loading: true,

      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 套餐管理表格数据
      packageList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      openPackage: false,
      openProduct: false,
      //套餐id
      title: '选择商品',

       // 商品列表
       productList: [],
      selectedProducts: [], // 存储选中商品的数组
    openProduct: false,
    loading: false,
    saveProductList: [], // 假设从服务器获取商品列表
    selectedProductIds: [], // 存储选中的商品 ID
     // 存储每个商品的数量
    productQuantities: [],
    packageId: 0,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        packageName: null,
        packagePicture: null,
        packagePrice: null,
        packageStatus: null
      },
      // 查询商品参数
      queryProductParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        productPhoto: null,
        productDetail: null,
        categoryId: null,
        specificationId: null,
        saleNum: null,
        isDiscount: null,
        isOnSale: null,
        discontStrength: null,
        storeId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getList();
    this.getProductList();

  },

  methods: {


  // 清除所有商品的选中状态
  clearAllSelections() {
    this.productQuantities = [];

  },
   // 查找已配置商品
   getPackageAssociation_start(packageId) {
  this.clearAllSelections();

  this.loading = true;
  getPackageAssociation(packageId).then(response => {
    this.saveProductList = response.rows;
    this.total = response.total;

    // 将已配置的商品数据设置到 selectedProductIds
    this.selectedProductIds = response.rows.map(product => ({
      productId: product.productId,
      productNum: product.productNum
    }));

    this.loading = false;
    console.log("已配置的商品", this.saveProductList);
  });
},
  //点击商品
  handleProductSelection(product) {
      const productId = product.productId;
      const existingProductIndex = this.selectedProductIds.findIndex(p => p.productId === productId);

      if (existingProductIndex >= 0) {
        this.selectedProductIds.splice(existingProductIndex, 1);
      } else {
        this.selectedProductIds.push({ productId, productNum: 1 });
      }
    },
    isProductSelected(productId) {
      return this.selectedProductIds.some(p => p.productId === productId);
    },
    getProductQuantity(productId) {
      const product = this.selectedProductIds.find(p => p.productId === productId);
      return product ? product.productNum : 1;
    },
    updateProductQuantity(productId, value) {
      const product = this.selectedProductIds.find(p => p.productId === productId);
      if (product) {
        product.productNum = Number(value);
      }
    },

  //保存配置商品按钮
  saveSelectedProducts() {
    // 检查是否选中了商品
    if (this.selectedProductIds.length === 0) {
      this.$message.warning('请至少选择一个商品');
      return;
    }

    // // 打印调试信息
    // console.log('选中的商品 ID:', this.selectedProductIds);
    // console.log('商品数量:', this.productQuantities);
    // console.log('套餐 ID:', this.packageId);

    // 发送请求新增套餐管理
    const data = {
      packageId: this.packageId,
      productQuantities: this.selectedProductIds
    };

      console.log(data)

    addPackageProduct(data)
      .then(response => {
        // 处理请求成功的情况
        console.log('保存成功:', response.data);
        this.$message.success('保存成功');
        this.openProduct = false; // 关闭对话框
        this.getList(); // 刷新列表或其他需要的操作
      })
      .catch(error => {
        // 处理请求失败的情况
        console.error('保存失败:', error);
        this.$message.error('保存失败，请重试');
      })
      .finally(() => {
        this.loading = false; // 确保无论成功还是失败都停止加载状态
      });

},

   //状态按钮禁言启用
    handleSwitchChange(row){
      const packageId = row.packageId || this.ids

      console.log(row.packageStatus)

  //  if(row.packageStatus == ){

  //  }
    updatePackage({
      packageId:packageId,
      packageStatus:row.packageStatus}).then(response => {
      this.$modal.msgSuccess("修改成功");
      this.getList();
    });

    },
    getProductList() {
      this.loading = true;
      listProduct(this.queryProductParams)
        .then(response => {
          this.productList = response.rows; // 根据实际返回数据结构调整
          this.total = response.total;
          this.loading = false;

          console.log(this.productList);
        })
        .catch(error => {
          console.error('Failed to fetch products:', error);
          this.loading = false;
        });
    },
    /** 查询套餐管理列表 */
    getList() {
      this.loading = true;
      listPackage(this.queryParams).then(response => {
        this.packageList = response.rows;
        this.total = response.total;
        this.loading = false;
      });

      console.log(  this.packageList)
    },
    // 取消按钮
    cancel() {
      // this.open = false;
      this.openProduct = false;
      this.openProduct = false;
      this.openPackage = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        packageId: null,
        packageName: null,
        packagePicture: null,
        packagePrice: null,
        packageStatus: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.packageId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.openPackage = true;
      this.title = "添加套餐管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const packageId = row.packageId || this.ids
      getPackage(packageId).then(response => {
        this.form = response.data;
        this.openPackage = true;
        this.title = "修改套餐管理";
      });
    },
     /** 配置菜单按钮操作 */
    handleProductUpdate(row){

      this.packageId = row.packageId || this.ids
      getPackage( this.packageId).then(response => {
        this.form = response.data;
        this.openProduct = true;
        this.title = "套餐配置管理";
      });
        //查找已配置商品
        this.getPackageAssociation_start(this.packageId);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.packageId != null) {
            updatePackage(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.openProduct = false;
              this.openPackage = false;
              this.getList();
            });
          } else {
            addPackage(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.openProduct = false;
              this.openPackage = false;
              this.getList();
            });
          }
        }
      });

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const packageIds = row.packageId || this.ids;
      this.$modal.confirm('是否确认删除套餐名为"' + row.packageName + '"的数据项？').then(function() {
        return delPackage(packageIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/package/export', {
        ...this.queryParams
      }, `package_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.product-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.3s ease;
}

.product-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
}

.product-checkbox {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.product-quantity {
  margin-top: 10px;
}

.product-image {

  max-width: 80%;
  height: auto;
}

.product-info {
  text-align: center;
}
</style>

